package util;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.google.protobuf.ByteString;

import network.MessageService;

import server.CommandFactories.CmdType;

import command.ExceptionResponseFactory.ExceptionResponse;
import command.protobuf.MessageBufProtoBuf.RpcMessage;

public class NetworkUtil {
	public static byte[] read(DataInputStream input) throws IOException {
		int count = input.readInt();
		byte[] content = new byte[count];
		input.read(content);
		return content;
	}

	public static void write(DataOutputStream output, byte[] content)
			throws IOException {
		output.writeInt(content.length);
		output.write(content);
		output.flush();
	}

	final static RpcMessage.Header.Builder headerBuilder = RpcMessage.Header
			.newBuilder();
	final static RpcMessage.Builder messageBuilder = RpcMessage.newBuilder();
	public static byte[] makeExResMessage(RpcMessage origin, String cause) throws IOException {
		ExceptionResponse ex = new ExceptionResponse(cause);
		ByteArrayOutputStream ao = new ByteArrayOutputStream();
		ex.write(ao);
		RpcMessage.Header originHeader = origin.getHeader();
		headerBuilder.setCmdType(CmdType.exceptionresponse.ordinal())
				.setID(originHeader.getID())
				.setFlag(originHeader.getFlag() | MessageService.RPC_EXCEPTION);
		messageBuilder.setHeader(headerBuilder);
		messageBuilder.setContent(ByteString.copyFrom(ao.toByteArray())).setHeader(headerBuilder.build());
		ao.reset();
		messageBuilder.build().writeTo(ao);
		return ao.toByteArray();
	}
}
